package com.htstar.ovms.device.util;

import com.htstar.ovms.common.core.constant.CommonConstants;
import com.htstar.ovms.common.core.util.R;
import com.htstar.ovms.common.minio.service.MinioTemplate;
import com.htstar.ovms.device.api.entity.ExportRecord;
import com.htstar.ovms.device.service.ExportRecordService;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ExprotUploadUtil {
    @Autowired
    private ExportRecordService exportRecordService;
    @Autowired
    private MinioTemplate minioTemplate;

    public R uploadExcel(String path, String fileNames, String bucketName, ExportRecord exportRecord) {
        minioTemplate.createBucket(bucketName);
        MinioClient minioClient = minioTemplate.getMinioClient();
        FileInputStream fileInputStream = null;
        String filePath = null;
        try {
            File file = new File("");
            filePath = file.getCanonicalPath();
            fileInputStream = new FileInputStream(new File(filePath + "/" + fileNames + ".xlsx"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }


//        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        String fileName = path + ".xlsx";
        Map<String, String> resultMap = new HashMap<>(4);
//		resultMap.put("bucketName", CommonConstants.BUCKET_NAME);
        resultMap.put("bucketName", bucketName);
        resultMap.put("fileName", fileName);
        resultMap.put("url", String.format("/admin/sys-file/%s/%s", "excel", fileName));

        try {
            minioTemplate.putObject(bucketName, fileName, fileInputStream);
            /*关闭文件，进行删除本地文件*/
            fileInputStream.close();
            //文件管理数据记录,收集管理追踪文件
//            fileLog(file, fileName);
        } catch (Exception e) {
            log.error("上传失败", e);
            return R.failed(e.getLocalizedMessage());
        }
        //更新状态
        exportRecord.setExportUrl(resultMap.get("url"));
        exportRecord.setExportStatus(2);
        exportRecordService.updateById(exportRecord);

        File file = new File(filePath + "/" + fileNames + ".xlsx");
        if (file.isFile() && file.exists()) {
            /*删除本地文件*/
            file.delete();
        }
        return R.ok(resultMap);
    }

}
